// pages/xd/xd.js
var api = require('../../utils/api.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopOrMan:0,
    loading:false,
    isInit: false,
    toView: '',
    size: 50,
    shopNum: 0,
    autoHeight: 0,
    shopBack: [],
    codeNum: "",
    userMessage: '',
    //城市
    city: '',
    //微信头像
    avatarUrl: '',
    //省份
    province: '',
    //性别
    gender: '',
    //微信名字
    nickName: '',
    storeChoose: '', //组件数据 店铺类型
    codeNum: '',
    tokenCode: '',
    login: '', //登录状态
    current: 1, //接口获取数据 1我的清单，2城市热卖
    currentTab: 0, //导航栏  0我的清单，1城市热卖  默认我的清单
    rightListId: '',
    // 右侧横向导航
    right_list: [],
    goodsList: [],
    color: "#9e9e9e",
    //数量
    inputNum: '',
    //购物车原有数量
    inputNum1: '',
    goodsName: '',
    goodsDetailsId: '',
    price: '',
    totalPrice: '',
    //起送数量
    startNum: '',
    indexs: 0,
    zindex: 0,
    sLoad:false,
    vipFlag:0
  },
  // 首页打电话
  callGetPhone: function () {
    wx.navigateTo({
      url: '/pages/kefu/kefu',
    })
  },
  // 搜索栏
  showInput: function() {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function() {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function() {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function(e) {
    this.setData({
      inputVal: e.detail.value
    });
  },
  //获取数量
  inputNum(e) {
    console.log(e)
    let that = this
    if (e.detail.value == "" || e.detail.value == 0 || e.detail.value < that.data.startNum) {
      that.setData({
        inputNum: that.data.inputNum1
      })
    } else {
      that.setData({
        inputNum: e.detail.value
      })
    }
  },

  //获取焦点
  bindconfocus(e) {
    let that = this
    // 获取点击父级的索引
    let indexs = e.currentTarget.dataset.index;
    // 获取选中的二级zindex索引
    let zindex = e.currentTarget.dataset.zindex;
    let goodsList = this.data.goodsList
    let price = 0
    let totalPrice = 0
    let amount = goodsList[indexs].goodsDetailsEntityList[zindex].amount
    if (goodsList[indexs].goodsDetailsEntityList[zindex].activitySeckillId == null) {
      if (wx.getStorageSync("vipFlag") == 1) {
        price = goodsList[indexs].goodsDetailsEntityList[zindex].salesPriceVip
        totalPrice = price * amount
      } else {
        price = goodsList[indexs].goodsDetailsEntityList[zindex].salesPrice
        totalPrice = price * amount
      }
    } else {
      price = goodsList[indexs].goodsDetailsEntityList[zindex].seckillPrice
      totalPrice = price * amount
    }
    this.setData({
      indexs: indexs,
      zindex: zindex,
      inputNum1: goodsList[indexs].goodsDetailsEntityList[zindex].amount,
      goodsName: goodsList[indexs].name,
      goodsDetailsId: goodsList[indexs].goodsDetailsEntityList[zindex].id,
      price,
      totalPrice,
      //起送数量
      startNum: goodsList[indexs].goodsDetailsEntityList[zindex].startNum,

    })
  },
  //失去焦点
  bindconfirm(e) {
    var that = this;

    if (that.data.inputNum == "") {

    } else {
      if (that.data.inputNum >= that.data.startNum) {
        let userInfoId = wx.getStorageSync("openId")
        let cityId = wx.getStorageSync("cityId")
        let goodsName = that.data.goodsName
        let goodsDetailsId = that.data.goodsDetailsId
        let price = that.data.detailPrice
        let amount = that.data.inputNum
        let totalPrice = that.data.totalPrice
        let goodsList = that.data.goodsList
        api.set_amount({
          cityId,
          userInfoId,
          goodsName,
          goodsDetailsId,
          amount,
          price,
          totalPrice
        }).then(res => {

          if (res.result) {
            goodsList[that.data.indexs].goodsDetailsEntityList[that.data.zindex].amount = that.data.inputNum;
            that.setData({
              goodsList: goodsList
            });
            if (res.data > 0) {
              wx.setTabBarBadge({
                index: 3,
                text: res.data //显示的内容 
              })
            } else {
              wx.hideTabBarRedDot({
                index: 3
              })
            }
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
            goodsList[that.data.indexs].goodsDetailsEntityList[that.data.zindex].amount = that.data.inputNum1;
            that.setData({
              goodsList: goodsList
            });
          }

        })

      } else {
        if (that.data.inputNum != "") {
          wx.showToast({
            title: '请输入最小起送数量' + that.data.startNum,
            icon: 'none'
          })
        }

      }

    }
  },
  bindconfirm1(e) {
    var that = this;
    if (that.data.inputNum >= that.data.startNum) {
      if (that.data.inputNum == "") {

      } else {
        let userInfoId = wx.getStorageSync("openId")
        let cityId = wx.getStorageSync("cityId")
        let goodsName = that.data.goodsName
        let goodsDetailsId = that.data.goodsDetailsId
        let price = that.data.detailPrice
        let amount = that.data.inputNum
        let totalPrice = that.data.totalPrice
        let goodsList = that.data.goodsList
        // carts[that.data.indexs].amount = that.data.inputNum;
        // that.setData({
        //   carts: carts
        // });

        api.set_amount({
          cityId,
          userInfoId,
          goodsName,
          goodsDetailsId,
          amount,
          price,
          totalPrice
        }).then(res => {

          if (res.result) {
            goodsList[that.data.indexs].goodsDetailsEntityList[that.data.zindex].amount = that.data.inputNum;
            that.setData({
              goodsList: goodsList
            });
            if (res.data > 0) {
              wx.setTabBarBadge({
                index: 3,
                text: res.data //显示的内容 
              })
            } else {
              wx.hideTabBarRedDot({
                index: 3
              })
            }
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
            goodsList[that.data.indexs].goodsDetailsEntityList[that.data.zindex].amount = that.data.inputNum1;
            that.setData({
              goodsList: goodsList
            });
          }

        })
      }
    } else {

      if (that.data.inputNum != "") {
        wx.showToast({
          title: '请输入最小起送数量' + that.data.startNum,
          icon: 'none'
        })
      }

    }
  },

  //点击跳转商品详情页
  // 跳转商品详情
  todetail: function(e) {
    //登录跳转商品详情界面
    let shopid = e.currentTarget.dataset.shopid
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + e.currentTarget.dataset.id + '&shopid=' + shopid,
    })

  },
  // nodetail() {
  //   wx.navigateTo({
  //     url: ''
  //   })
  // },
  //滑动切换
  swiperTab: function(e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current,
      current: e.detail.current * 1 + 1
    });
    //再次调用
    //商品展示列表
    that.getGoodsLists()
  },
  //点击切换  清单 城市热卖
  clickTab: function(e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current, //类型切换
        current: e.target.dataset.current * 1 + 1 //数字类型转换  传给后台数据
      })
    }
    //再次调用
    api.right_list({
      rank: that.data.current, //必传     1我的清单，2城市热卖
      cityId: wx.getStorageSync("cityId"), //必传 城市Id
      userId: wx.getStorageSync("openId"), //用户ID
    }).then(res => {
      if (res.result) {
        that.setData({
          right_list: res.object,
        })
      }
    })
    //商品展示列表
    that.getGoodsLists()

  },
  // 上方横向导航

  switchTap2: function(e) {
    console.log(e)
    var that = this;
    that.setData({
      rightListId: e.currentTarget.dataset.id,
      toView: e.currentTarget.dataset.itemid
    })
  },
  jumpTo: function(e) {
    // 获取标签元素上自定义的 data-opt 属性的值
    let target = e.currentTarget.dataset.opt;
    this.setData({
      toView: target
    })
  },


  // 点击关注
  follow: function(e) {
    var that = this;
    // 获取选中的index索引
    var index = e.currentTarget.dataset.index;
    // 获取到商品列表数据
    var goodsList = that.data.goodsList;
    // 循环数组数据，判断----选中/未选中[selected]
    goodsList[index].follow = !goodsList[index].follow;
    // 重新渲染数据
    that.setData({
      goodsList: goodsList,
    })
    //取消关注 接口
    api.delExample({
      goodsId: this.data.goodsList[index].id, //商品id
      createid: wx.getStorageSync("openId"), //用户id
      cityId: wx.getStorageSync("cityId"), //必传 城市Id
    }).then(res => {
      if (res.result) {

        wx.showToast({
          title: '取消成功',
          icon: "none",
          duration: 1000,
        })

        that.getGoodsLists()
      }
    })
  },

  //规格
  more: function(e) {
    let that = this
    // 获取选中的index索引
    var index = e.currentTarget.dataset.index;
    // 获取到商品列表数据
    var goodsList = that.data.goodsList;
    // 循环数组数据，判断----规格 --收起
    goodsList[index].choice = !goodsList[index].choice;
    //重新渲染数据
    that.setData({
      goodsList
    })
  },
  //点击加号变化
  btnVehicle: function(e) {
    let that = this
    // 获取点击父级的索引
    let index = e.currentTarget.dataset.index;
    // 获取选中的二级zindex索引
    var zindex = e.currentTarget.dataset.zindex;
    let goodsList = that.data.goodsList //商品列表数组
    goodsList[index].goodsDetailsEntityList[zindex].vehicleFlag = !goodsList[index].goodsDetailsEntityList[zindex].vehicleFlag;
    // 获取商品数量
    let amount = goodsList[index].goodsDetailsEntityList[zindex].amount;
    let userInfoId = wx.getStorageSync("openId") //用户ID
    let cityId = wx.getStorageSync("cityId") //城市ID
    let goodsName = goodsList[index].name //商品名
    let goodsDetailsId = goodsList[index].goodsDetailsEntityList[zindex].id //商品id
    let startNum = goodsList[index].goodsDetailsEntityList[zindex].startNum * 1 //起送数量
    // 点击递增
    amount = startNum;
    
    let price = 0
    let totalPrice = 0
    if (goodsList[index].goodsDetailsEntityList[zindex].activitySeckillId == null) {
      if (wx.getStorageSync("vipFlag") == 1) {
        price = goodsList[index].goodsDetailsEntityList[zindex].salesPriceVip
        totalPrice = price * amount
      } else {
        price = goodsList[index].goodsDetailsEntityList[zindex].salesPrice
        totalPrice = price * amount
      }
    } else {
      price = goodsList[index].goodsDetailsEntityList[zindex].seckillPrice
      totalPrice = price * amount
    }
    //购物车接口
    api.goodsNumber({
      cityId,
      userInfoId,
      goodsName,
      goodsDetailsId,
      amount,
      price,
      totalPrice
    }).then(res => {
      if (res.result) {
        if (res.data > 0) {
          wx.setTabBarBadge({
            index: 3,
            text: res.data //显示的内容 
          })
        }
        goodsList[index].goodsDetailsEntityList[zindex].amount = amount;
        // 重新渲染 ---显示新的数量
        that.setData({
          goodsList: goodsList
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })

  },

  //添加数量
  addNum: function(e) {
    let that = this
    // 获取点击父级的索引
    let index = e.currentTarget.dataset.index;
    // 获取选中的二级zindex索引
    var zindex = e.currentTarget.dataset.zindex;
    // 获取商品数据
    let goodsList = that.data.goodsList;
    // 获取商品数量
    let amount = goodsList[index].goodsDetailsEntityList[zindex].amount;
    let goodsDetailsId = goodsList[index].goodsDetailsEntityList[zindex].id //商品id
    let userInfoId = wx.getStorageSync("openId") //用户ID
    let cityId = wx.getStorageSync("cityId") //城市ID
    let goodsName = goodsList[index].name //商品名
    // 点击递增
    amount = amount + 1;
    let price = 0
    let totalPrice = 0
    if (goodsList[index].goodsDetailsEntityList[zindex].activitySeckillId == null) {
      if (wx.getStorageSync("vipFlag") == 1) {
        price = goodsList[index].goodsDetailsEntityList[zindex].salesPriceVip
        totalPrice = price * amount
      } else {
        price = goodsList[index].goodsDetailsEntityList[zindex].salesPrice
        totalPrice = price * amount
      }
    } else {
      price = goodsList[index].goodsDetailsEntityList[zindex].seckillPrice
      totalPrice = price * amount
    }
    //购物车接口
    api.goodsNumber({
      cityId,
      userInfoId,
      goodsName,
      goodsDetailsId,
      amount,
      price,
      totalPrice
    }).then(res => {
      if (res.result) {
        if (res.data > 0) {
          wx.setTabBarBadge({
            index: 3,
            text: res.data //显示的内容 
          })
        }
        // 重新渲染 ---显示新的数量
        goodsList[index].goodsDetailsEntityList[zindex].amount = amount;
        that.setData({
          goodsList: goodsList
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  //减少数量
  reduceNum(e) {
    let that = this
    // 获取点击父级的索引
    let index = e.currentTarget.dataset.index;
    // 获取选中的二级zindex索引
    var zindex = e.currentTarget.dataset.zindex;
    // 获取商品数据
    let goodsList = that.data.goodsList;
    // 获取商品数量
    let amount = goodsList[index].goodsDetailsEntityList[zindex].amount;
    let userInfoId = wx.getStorageSync("openId") //用户ID
    let cityId = wx.getStorageSync("cityId") //城市ID
    let goodsName = goodsList[index].name //商品名
    let goodsDetailsId = goodsList[index].goodsDetailsEntityList[zindex].id //商品id
    if (amount == startNum) {
      amount = 0
    } else {
      amount = amount - 1;
    }

    let price = 0
    let totalPrice = 0
    if (goodsList[index].goodsDetailsEntityList[zindex].activitySeckillId == null) {
      if (wx.getStorageSync("vipFlag") == 1) {
        price = goodsList[index].goodsDetailsEntityList[zindex].salesPriceVip
        totalPrice = price * amount
      } else {
        price = goodsList[index].goodsDetailsEntityList[zindex].salesPrice
        totalPrice = price * amount
      }
    } else {
      price = goodsList[index].goodsDetailsEntityList[zindex].seckillPrice
      totalPrice = price * amount
    }
    
    //购物车接口
    api.goodsNumber({
      cityId,
      userInfoId,
      goodsName,
      goodsDetailsId,
      amount,
      price,
      totalPrice
    }).then(res => {
      goodsList[index].goodsDetailsEntityList[zindex].amount = amount;
      // 重新渲染 ---显示新的数量
      that.setData({
        goodsList: goodsList
      });
      if (res.data > 0) {
        wx.setTabBarBadge({
          index: 3,
          text: res.data //显示的内容 
        })
      } else {
        wx.hideTabBarRedDot({
          index: 3
        })
      }
    })
  },
  getGoodsLists: function() {
    //商品展示列表
    api.xdgoodsList({
      rank: this.data.current, //必传     1我的清单，2城市热卖
      cityId: wx.getStorageSync("cityId"), //必传 城市Id
      userId: wx.getStorageSync("openId"), //用户ID
      page: {
        startPage: false, //上滑加载
        size: this.data.size //初次渲染
      }
    }).then(res => {
      if (res.result) {
        if(wx.getStorageSync('type') == "2"){
          res.object.records.forEach(v=>{
            v.goodsDetailsEntityList.forEach(j=>{
              api.roleSwitch(j)
            })
          })
        }
        //创建新的空数组
        let dataNew = [];
        //遍历商品列表
        for (var i = 0; i < res.object.records.length; i++) { //遍历数组 给数组元素加上隐藏
          //给数组元素加上 规格 收起
          res.object.records[i].choice = true;
          //给数组元素加上 关注
          res.object.records[i].follow = true;
          res.object.records[i].vehicleFlag = false;
          res.object.records[i].goodsDetailsEntityList.forEach(v => {
            if (v.amount > 0) {
              res.object.records[i].choice = false;
            }
          })
        }
        this.setData({
          goodsList: res.object.records,
          sLoad:true
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
   
    wx.getSystemInfo({
      success: function(res) {
        let clientHeight = res.windowHeight;
        let clientWidth = res.windowWidth;
        let ratio = 750 / clientWidth;
        let height = clientHeight * ratio;
        that.setData({
          autoHeight: height,
        });
      }
    })

  },
  getShopSum() {
    api.get_cart({
        cityId: wx.getStorageSync("cityId"),
        userId: wx.getStorageSync("openId"),
        page: {}
      })
      .then(res => {
        let getSum = res.data.body.getSum;
        if (getSum > 0) {
          wx.setTabBarBadge({
            index: 3,
            text: getSum + '' //显示的内容 
          })
        } else {
          wx.hideTabBarRedDot({
            index: 3
          })
        }
      })

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    //判断登录
    that.setData({
      login: wx.getStorageSync('token') ? wx.getStorageSync('codeNum') == 99 ? true : false : false,
      codeNum: wx.getStorageSync('codeNum'),
      tokenCode: wx.getStorageSync('token'),
      userMessage: wx.getStorageSync('userMessage'),
      vipFlag : wx.getStorageSync('vipFlag'),
      shopOrMan: wx.getStorageSync("type")
    })
    if(that.data.login){
      that.getShopSum()
    }
    that.setData({
      city: that.data.city,
      avatarUrl: that.data.avatarUrl,
      province: that.data.province,
      gender: that.data.gender,
      nickName: that.data.nickName,
    })
    //插件接口
    if(wx.getStorageSync('codeNum') == 104){
      api.shopBack({
        cityId: wx.getStorageSync("cityId")
      })
      .then(res => {
        if (res.result) {
          let len = res.body.getShopInfo.length - 1;
          let shopBack = res.body.getShopInfo[len]
          this.setData({
            shopBack,
            codeNum: wx.getStorageSync("codeNum")
          })
        }
      })
    }
    if (that.data.codeNum == 104) {
      wx.showToast({
        title: '您的店铺正在审核中！',
        icon: 'none',
        duration: 1000
      })
    } else if (that.data.codeNum == 105) {
      wx.showToast({
        title: '抱歉，您的店铺未通过审核，请重新注册！',
        icon: 'none',
        duration: 1000
      })
    }
    api.shopType({}).then(res => {
      if (res.result) {
        this.setData({
          storeChoose: res.object,
        })
      }
    })
    //我的清单-------城市热卖 分类查询
    api.right_list({
      rank: that.data.current, //必传     1我的清单，2城市热卖
      cityId: wx.getStorageSync("cityId"), //必传 城市Id
      userId: wx.getStorageSync("openId"), //用户ID
    }).then(res => {
      if (res.result) {
        that.setData({
          right_list: res.object,
        })
      }
    })

    that.getGoodsLists()
  },

  handleSearch() {
    wx.navigateTo({
      url: '/pages/search_index/search_index',
    })
  },
  onShareAppMessage() {
    return {
      title: '京天鲜生, 生鲜管家',
      path: '/pages/index/index',
      imageUrl: '../../images/share.jpeg', // 可以更换分享的图片
    }
  },
  //上滑加载
  scrollBottom(){
    let size = this.data.size
    size = size + 50
    //商品展示列表
    api.xdgoodsList({
      rank: this.data.current, //必传     1我的清单，2城市热卖
      cityId: wx.getStorageSync("cityId"), //必传 城市Id
      userId: wx.getStorageSync("openId"), //用户ID
      page: {
        startPage: false, //上滑加载
        size: size //初次渲染
      }
    }).then(res => {
      if (res.result) {
        if(wx.getStorageSync('type') == "2"){
          res.object.records.forEach(v=>{
            v.goodsDetailsEntityList.forEach(j=>{
              api.roleSwitch(j)
            })
          })
        }
        //创建新的空数组
        let dataNew = [];
        //遍历商品列表
        for (var i = 0; i < res.object.records.length; i++) { //遍历数组 给数组元素加上隐藏
          //给数组元素加上 规格 收起
          res.object.records[i].choice = true;
          //给数组元素加上 关注
          res.object.records[i].follow = true;
          res.object.records[i].vehicleFlag = false;
          res.object.records[i].goodsDetailsEntityList.forEach(v => {
            if (v.amount > 0) {
              res.object.records[i].choice = false;
            }
          })
        }
        this.setData({
          goodsList: res.object.records,
          size,
        })
      }
    })
  }
})